package happy.diandiankong.api.resource;

import com.google.common.collect.ImmutableMap;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * Title.
 * <p>
 * Description.
 *
 * @author Bill Lv {@literal <billcc.lv@hotmail.com>}
 * @version 1.0
 * @since 2016-10-29
 */
@Path("/api/blockly")
@Produces(MediaType.APPLICATION_XML)
@Api("/blockly")
public class BlocklyResource {
    static final Logger LOGGER = LoggerFactory.getLogger(BlocklyResource.class);

    @POST
    @Path("/xml-parse")
    @ApiOperation("Parse XML")
    public Response parseXml(@Context HttpServletRequest request) throws Exception {
        final String payload = getPayload(request);
        LOGGER.info("payload: {}", payload);
        return Response.ok(
                ImmutableMap.of("code", 0, "message", "success"))
                .build();
    }

    private String getPayload(HttpServletRequest request) throws IOException {
        try (BufferedReader reader = request.getReader()) {
            StringBuilder stringBuilder = new StringBuilder();
            String string;
            while ((string = reader.readLine()) != null) {
                stringBuilder.append(string);
            }
            return stringBuilder.toString();
        }
    }
}
